import React from 'react';
import SearchBar from '../SearchBar'
import PageTable from '../PageTable';

interface ITableContainerProps {
	className?: string,
	onSearch?: (data: object) => void
}
export default class extends React.Component<ITableContainerProps> {
	static defaultProps = {
		className: 'default-classname'
	}
	constructor(props: ITableContainerProps) {
		super(props)
	}
	private refTable: any
	handleSearch = (data: object, props: ITableContainerProps) => {
		const { onSearch } = props;
		if (onSearch) {
			return onSearch(data)
		}
		this.refTable && this.refTable.fetchData(data);
	}
	setTableRef = (refTable: string) => {
		this.refTable = refTable
	}
	render() {
		const { children, className } = this.props;
		let childs = React.Children.map(children, (child: any) => {
			if (child.type === SearchBar) {
				return React.cloneElement(child, {
					onSearch: (data: object) => this.handleSearch(data, child.props),
				})
			} else if (child.type === PageTable) {
				return React.cloneElement(child, { ref: this.setTableRef })
			}
			return child
		});

		return (
			<div className={`table-container ${className}`}>
				{childs}
			</div>
		)
	}
}